package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"weibo-manager/cache"
	"weibo-manager/model"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	title := c.Query("title")
	var wei []model.WeiBO
	redis_key := "wei_list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("title like ?", "%"+title+"%").Offset(offset).Limit(size).Find(&wei)
		jsonData, _ := json.Marshal(&wei)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &wei)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "展示成功", "data": wei})

}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var wei model.WeiBO
	redis_key := "wei_detail_id_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&wei)
		jsonData, _ := json.Marshal(&wei)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &wei)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "展示成功", "data": wei})
}
func Add(c *gin.Context) {
	contents := c.PostForm("contents")
	comment := model.Comment{
		Contents: contents,
	}
	err := model.DB.Create(&comment).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
}
func Comment(c *gin.Context) {
	var comment []model.Comment
	redis_key := "data"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&comment)
		jsonData, _ := json.Marshal(&comment)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &comment)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "展示成功", "data": comment})
}
